<?php

namespace Proyecto\MainBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Proyecto\MainBundle\Entity\Item;
use Proyecto\MainBundle\Form\ItemType;
use Symfony\Component\HttpFoundation\Response;


class ItemController extends Controller
{

    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('ProyectoMainBundle:Item')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    
    /**
     * Devuelve el tipo de un item.
     *
     * 
     * @Route("/user/item/tipoItem", name="tipo_item_json", options={"expose"=true})
     * 
     * @Method("POST")
     * @Template()
     */
    public function tipoItemAction()
    {
        /*$parameters=$this->getRequest()->request->all();
        $iditem=$parameters['iditem'];
        $iditem = $this->getRequest()->request->get('iditem');*/
        $iditem= 19;
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('ProyectoMainBundle:Item')->find($iditem);
        $respuesta = ("{'tipo':'".$entity->getTipo()."'}");
        $response = new Response();
        $response->setContent($respuesta);
        return $response;
    }
    
    /**
     * Lista todos los items pertenecientes a una categoria que pueden ser cargados en un cv.
     *
     * @Route("/user/listItemsJson", name="list_item_json", options={"expose"=true})
     * @Method("POST")
     * @Template()
     */
    public function listJsonAction()
    {
        $parameters=$this->getRequest()->request->all();
        $em = $this->getDoctrine()->getManager();
        $query1 = $em->createQuery("SELECT i
                                   FROM ProyectoMainBundle:Item i
                                   WHERE i.categoria = :categoria AND i.activo = 1 AND i.repetible = 1"); 
        $query2 = $em->createQuery("SELECT i
                                   FROM ProyectoMainBundle:Item i
                                   WHERE i.categoria = :categoria AND i.activo = 1 AND i.repetible = 0 AND NOT EXISTS (SELECT d 
                                                                                                   FROM ProyectoMainBundle:DatoItem d
                                                                                                   WHERE d.idUsuario = :usuario AND d.idItem = i.id)");
        $query1->setParameter('categoria',$parameters['idcategoria']);
        $query2->setParameter('usuario',$parameters['usuario']);
        $query2->setParameter('categoria',$parameters['idcategoria']);
        $items1 = $query1->getResult();
        $items2 = $query2->getResult();
        $items = array_merge($items1,$items2);
        $respuesta="[";
        if ($items){
	  foreach ($items as $item){
		$respuesta.="{'id_item':'".$item->getId()."','descripcion':'".$item->getDescripcion()."'},";
	}
	$respuesta=trim($respuesta,',');
	$respuesta.="]";
	}else{ $respuesta="{'cantidad':'0'}";}

        $response = new Response();
        $response->setContent($respuesta);
        return $response;
    }

    /**
     * Creates a new Item entity.
     *
     * @Route("/", name="item_create", options={"expose"=false})
     * @Method("POST")
     * @Template("ProyectoMainBundle:Item:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new Item();
        $form = $this->createForm(new ItemType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('item_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }


    public function newAction()
    {
        $entity = new Item();
        $form   = $this->createForm(new ItemType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ProyectoMainBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ProyectoMainBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $editForm = $this->createForm(new ItemType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ProyectoMainBundle:Item')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Item entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ItemType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('item_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('ProyectoMainBundle:Item')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Item entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('item'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
     /**
     * Lista todos los items pertenecientes a una categoria.
     *
     * @Route("/admin/item/listItems", name="list_item", options={"expose"=true})
     * @Method("POST")
     * @Template()
     */
    public function listAction()
    {
        $parameters=$this->getRequest()->request->all();
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery("SELECT i FROM ProyectoMainBundle:Item i WHERE i.categoria =:categoria AND i.activo =1 AND NOT EXISTS (SELECT e.valor FROM ProyectoMainBundle:Elemento e WHERE e.tipo = 'item' AND e.plantilla =:plantilla AND e.valor = i.id)");
        $query->setParameter('categoria',$parameters['idcategoria']);
        $query->setParameter('plantilla',$parameters['idplantilla']);
        $items = $query->getResult();
        $respuesta="[";
        if ($items){
	  foreach ($items as $item){
		$respuesta.="{'id_item':'".$item->getId()."','descripcion':'".$item->getDescripcion()."'},";
	}
	$respuesta=trim($respuesta,',');
	$respuesta.="]";
	}else{ $respuesta="{'cantidad':'0'}";}

        $response = new Response();
        $response->setContent($respuesta);
        return $response;
    }

}
